//
//  NewsViewController.m
//  WY
//
//  Created by lanou3g on 16/5/9.
//  Copyright © 2016年 pcc. All rights reserved.
//

#import "NewsViewController.h"
#import "ChannelModel.h"
#import "ChannelLabel.h"
#import "ChannelCell.h"
#import "NewsController.h"

@interface NewsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
//频道滚动视图
@property (weak, nonatomic) IBOutlet UIScrollView *scollView;
//新闻视图
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//布局参数
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
//频道数组
@property (nonatomic, strong) NSArray *channelList;
//当前显示标签索引
@property (nonatomic, assign) NSInteger currentIndex;

@property (nonatomic, strong) NSMutableDictionary *newsVCCahe;

@end

@implementation NewsViewController
//搜索
- (IBAction)searchBtn:(UIBarButtonItem *)sender {
}
//小菜单
- (IBAction)menuBtn:(UIBarButtonItem *)sender {
}
//添加频道
- (IBAction)addChannelBtn:(UIButton *)sender {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupView];
    [self loadChannelData];
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    // Do any additional setup after loading the view.
}
/**
 *  subviews layout
 */
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self setupView];
}

- (void)setupView {
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.layout.itemSize = self.collectionView.bounds.size;
    //滚动方向
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //隐藏横向滚动条
    self.collectionView.showsHorizontalScrollIndicator = NO;
    //列间距
    self.layout.minimumLineSpacing = 0;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.scollView.showsHorizontalScrollIndicator = NO;
    
}

- (void)loadChannelData {
    
    NSArray *channels = [ChannelModel channelArrData];
    channels = [channels sortedArrayUsingComparator:^NSComparisonResult(ChannelModel *  _Nonnull obj1, ChannelModel *  _Nonnull obj2) {

        
        return [obj1.tid compare:obj2.tid];
        
    }];
    __block CGFloat labelX = 0;
    [channels enumerateObjectsUsingBlock:^(ChannelModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //计算坐标
        CGFloat labelY = 0;
        CGFloat labelH = self.scollView.bounds.size.height;
        
        ChannelLabel *label = [ChannelLabel channelLabelWithTitle:obj.tname];
        CGFloat labelW = label.bounds.size.width;
//        NSLog(@"%f",label.bounds.size.width);
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        labelX += labelW;
        __block typeof(label) weakLabel = label;
        __block typeof(self) weakSelf = self;
        [label setClickchannel:^{
            // switch viewController
            [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:idx inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
            ChannelLabel *currentChannel = weakSelf.scollView.subviews[weakSelf.currentIndex];
            NSLog(@"%ld",weakSelf.currentIndex);
            //当前为小标题(点击后当前变成前一个标题)
            currentChannel.scale = 0;
            // Click change big
            weakLabel.scale = 1;
            weakSelf.currentIndex = idx;
            NSLog(@"当前lable:%ld",weakSelf.currentIndex);
            [weakSelf adjustScrollViewContentOffset];
           
        }];
        // The first selected by default
        if (idx == 0) {
            label.scale = 1;
        }
        [self.scollView addSubview:label];
        
    }];
    // set the boundary of scroll
    self.scollView.contentSize = CGSizeMake(labelX, 0);
    self.channelList = channels;
    [self.collectionView reloadData];
}
- (void)adjustScrollViewContentOffset {
    // take out the currently selected channel
    ChannelLabel *channel = self.scollView.subviews[self.currentIndex];
    CGFloat offsetX = channel.center.x - CGRectGetWidth(self.scollView.frame) * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = self.scollView.contentSize.width - CGRectGetWidth(self.scollView.frame);
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    [self.scollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    NSLog(@"适应偏移设置");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UICollectionViewDataSource method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.channelList.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ChannelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //把旧的view从缓存中移除
    [cell.newsController.view removeFromSuperview];
    
    ChannelModel *channel = self.channelList[indexPath.item];
    //  Take out the corresponding channel controller
    NewsController *news = [self newsControllerWithChannel:channel];
    if (![self.childViewControllers containsObject:news]) {
        NSLog(@"添加子控制器");
        // 把控制器添加到子控制器，否则会影响响应者链条---必须注意
        [self addChildViewController:news];
    }

    news.view.frame = cell.contentView.bounds;
    [cell.contentView addSubview:news.view];
    cell.newsController = news;
    return cell;
}

- (NewsController *)newsControllerWithChannel:(ChannelModel *)channel {
    NewsController *news = [self.newsVCCahe objectForKey:channel.tid];
    if (!news) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"News" bundle:nil];
        news = [sb instantiateViewControllerWithIdentifier:@"News"];
        news.channelId = channel.tid;
        [self.newsVCCahe setObject:news forKey:channel.tid];
    }
    NSLog(@"%@",self.newsVCCahe);
    return news;
}

//懒加载
- (NSMutableDictionary *)newsVCCahe {
    if (!_newsVCCahe) {
        _newsVCCahe = [NSMutableDictionary dictionary];
    }
    return _newsVCCahe;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    ///问题:indexPathsForVisibleItems:索引路径Fo r可见的物品
    NSArray *indexPaths = self.collectionView.indexPathsForVisibleItems;
    ChannelLabel *currentChannel = self.scollView.subviews[self.currentIndex];
    __block ChannelLabel *nextChannel;
    [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.item != self.currentIndex) {
            nextChannel = self.scollView.subviews[obj.item];
        }
         NSLog(@"滑动结束nextchannel:%@,%ld",nextChannel,self.currentIndex);
    }];
    if (!nextChannel) {
        return;
    }
    NSLog(@"重新设置偏移");
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat scale = ABS(offsetX /scrollView.bounds.size.width - self.currentIndex);
    CGFloat currentScale = 1 - scale;
    nextChannel.scale = scale;
    currentChannel.scale = currentScale;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    self.currentIndex = (NSInteger)offsetX / scrollView.bounds.size.width;
    NSLog(@"减速结束");
    [self adjustScrollViewContentOffset];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
